/*
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.mrd.gtimpframe.singlewindow;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mrd.framework.utils.SpringUtils;
import com.mrd.gtimp.service.client.CtmsServiceClient;
import com.mrd.gtimpframe.entity.CargoDeclaRecord;
import com.mrd.gtimpframe.entity.ComDeclaProp;
import com.mrd.gtimpframe.entity.ComDeclaWay;
import com.mrd.gtimpframe.entity.Declaration;
import com.mrd.gtimpframe.entity.LicenseDocu;
import com.mrd.gtimpframe.service.CargoDeclaRecordService;
import com.mrd.gtimpframe.service.ComDeclaWayService;
import com.mrd.gtimpframe.service.DeclarationService;
import com.mrd.gtimpframe.service.HgDataService;
import com.mrd.gtimpframe.service.QPCompanyService;
import com.mrd.gtimpframe.singlewindow.entity.SWClientResp;
import com.mrd.gtimpframe.singlewindow.entity.SWClientRespReceipt;
import com.mrd.redis.JedisClientClusterImpl;
import com.mrd.util.FreeMarkerUtils;
import com.mrd.util.FtpUtil;
import com.mrd.util.LoginUtil;
import com.mrd.util.StringUtils;
import com.mrd.util.io.UnicodeReader;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import util.XMLUtils;

/**
 * Created by dusy on 2017/9/20.
 */
@Service
public class SingleWindow {
    @Autowired
    private DeclarationService declarationService;
    @Autowired
    private HgDataService hgDataService;
    @Autowired
    private ComDeclaWayService comDeclaWayService;
    @Autowired
    private CargoDeclaRecordService cargoDeclaRecordService;
    @Autowired
    private JedisClientClusterImpl jedisClientCluster;

    public static Map<String, Thread> uploadThread = new HashMap<>();
    public static Map<String, Thread> downloadThread = new HashMap<>();

    /**
     * 生成xml报文
     *
     * @param did 报关单id
     * @return 报文路径
     */
    public String buildXML(String did) throws URISyntaxException {
        String xmlFilePath = null;
        Declaration declaration = declarationService.selectByPrimaryKey4SingleWindow(did);
        if (declaration != null) {
            declaration = changeToSingleWindowCode(declaration);
            String directory = this.getClass().getResource("").toURI().getPath();
            String fileName = "declaration.ftl";
            Map<String, Object> params = new HashMap<>();
            params.put("declaration", declaration);
            File xmlDir = new File(getGtimpXMLDirPath());
            if (!xmlDir.exists()) {
                xmlDir.mkdirs();
            }
            xmlFilePath = getGtimpXMLDirPath() + File.separator + declaration.getBusinessId() + "_" + declaration.getId() + ".xml";
            FreeMarkerUtils.toXML(directory, fileName, params, xmlFilePath);
        }
        return xmlFilePath;
    }

    private Declaration changeToSingleWindowCode(Declaration declaration) {
        String trnRel = "直航".equals(declaration.getDataType()) ? "0" : "1";
        declaration.setDataType(trnRel);
        if (declaration.getDealMode() != null) {
            declaration.setDealMode(hgDataService.getCodeByName(declaration.getDealMode(), "HGD_9"));
        }
        if (declaration.getFreight3() != null) {
            declaration.setFreight3(hgDataService.getCodeByName(declaration.getFreight3(), "HGD_1"));
        }
        if (declaration.getPremium3() != null) {
            declaration.setPremium3(hgDataService.getCodeByName(declaration.getPremium3(), "HGD_1"));
        }
        if (declaration.getOtherfee3() != null) {
            declaration.setOtherfee3(hgDataService.getCodeByName(declaration.getOtherfee3(), "HGD_1"));
        }
        if (declaration.getCustomsTypeCode() == null) {
            String customsTypeCode = "";
            String customsType = declaration.getCustomsType();
            if (customsType != null) {
                if (customsType.contains("普通") || customsType.contains("有纸")) {
                    customsTypeCode = "0";
                } else if (customsType.contains("通关") && customsType.contains("无纸化")) {
                    customsTypeCode = "M";
                } else if (customsType.contains("清单") && customsType.contains("无纸")) {
                    customsTypeCode = "D";
                } else if (customsType.contains("清单")) {
                    customsTypeCode = "L";
                }
            }
            declaration.setCustomsTypeCode(customsTypeCode);
        }
        String wrapType = "7";
        if (declaration.getGoodsPackageCode() == null) {
            if (declaration.getGoodsPackage() != null) {
                switch (declaration.getGoodsPackage()) {
                    case "木箱":
                        wrapType = "1";
                        break;
                    case "纸箱":
                        wrapType = "2";
                        break;
                    case "桶装":
                        wrapType = "3";
                        break;
                    case "散装":
                        wrapType = "4";
                        break;
                    case "托盘":
                        wrapType = "5";
                        break;
                    case "包":
                        wrapType = "6";
                        break;
                    default:
                        wrapType = "7";
                }
            }
            declaration.setGoodsPackageCode(wrapType);
        }
        if (declaration.getFreight1() != null) {
            declaration.setFreight1(toRate(declaration.getFreight1()));
            if (declaration.getFreight1() == null) {
                declaration.setFreight2(null);
                declaration.setFreight3(null);
            }
        }
        if (declaration.getPremium1() != null) {
            declaration.setPremium1(toRate(declaration.getPremium1()));
            if (declaration.getPremium1() == null) {
                declaration.setPremium2(null);
                declaration.setPremium3(null);
            }
        }
        if (declaration.getOtherfee1() != null) {
            declaration.setOtherfee1(toRate(declaration.getOtherfee1()));
            if (declaration.getOtherfee1() == null) {
                declaration.setOtherfee2(null);
                declaration.setOtherfee3(null);
            }
        }
        declaration.setSpecialRelationshipConfirm("1".equals(declaration.getSpecialRelationshipConfirm()) ? "0" : "1");
        declaration.setPriceImpactConfirm("1".equals(declaration.getPriceImpactConfirm()) ? "0" : "1");
        declaration.setPaymentRoyaltilsConfirm("1".equals(declaration.getPaymentRoyaltilsConfirm()) ? "0" : "1");
        if (declaration.getLicenseDocuList() != null) {
            boolean hasLicenseDocu = false;
            for (LicenseDocu licenseDocu : declaration.getLicenseDocuList()) {
                if (licenseDocu.getSuifudanCo() != null || licenseDocu.getSuifudanNo() != null) {
                    hasLicenseDocu = true;
                    break;
                }
            }
            if (!hasLicenseDocu) {
                declaration.setLicenseDocuList(null);
            }
        }
        dealCommodityList(declaration);
        return declaration;
    }

    /**
     * 商品信息处理
     */
    private void dealCommodityList(Declaration declaration) {
        if (declaration != null && declaration.getCommodityList() != null) {
            declaration.getCommodityList().forEach(commodity -> {
                if (commodity.getGoodsMode() != null) {
                    String[] modes = commodity.getGoodsMode().split("\\|");
                    switch (modes[0]) {
                        case "无品牌":
                            modes[0] = "0";
                            break;
                        case "境内自主品牌":
                            modes[0] = "1";
                            break;
                        case "境内收购品牌":
                            modes[0] = "2";
                            break;
                        case "境外品牌(贴牌生产)":
                            modes[0] = "3";
                            break;
                        case "境外品牌(其它)":
                            modes[0] = "4";
                            break;
                    }
                    switch (modes[1]) {
                        case "出口货物在最终目的国(地区)不享受优惠关税":
                            modes[1] = "0";
                            break;
                        case "出口货物在最终目的国(地区)享受优惠关税":
                            modes[1] = "1";
                            break;
                        case "不能确定在最终目的国(地区)享受优惠关税":
                            modes[1] = "2";
                            break;
                        case "不适用于进口报关单":
                            modes[1] = "3";
                            break;
                    }
                    StringBuffer goodMode = new StringBuffer();
                    for (String mode : modes) {
                        goodMode.append("|" + mode);
                    }
                    goodMode.deleteCharAt(0);
                    commodity.setGoodsMode(goodMode.toString());
                }
            });
        }
    }

    private String toRate(String str) {
        if (str.contains("率")) {
            return "1";
        } else if (str.contains("单价")) {
            return "2";
        } else if (str.contains("总价")) {
            return "3";
        } else {
            return null;
        }
    }

    /**
     * 根据报关单ID，将报关资料通过ftp传到对应客户端文件夹下
     *
     * @param declarationId 报关单ID
     */
    public void up2cargoDecla(String declarationId) {
        // 查公司ID
        String comId = LoginUtil.getLoginUser().getCompany().getId();
        // 查公司对应单一窗口配置
        ComDeclaWay query = comDeclaWayService.findByComId(comId);
        if (query == null) {
            throw new RuntimeException("没有开通国版单一窗口");
        }
        Declaration declaration = declarationService.selectByPrimaryKey(declarationId);
        // 查询报关状态
        List<CargoDeclaRecord> records = cargoDeclaRecordService.selectByDid(Collections.singletonList(declarationId));
        if (records == null || records.size() == 0) {// 无有效记录则新建报关记录
            cargoDeclaRecordService.newRecord(declaration, ComDeclaWay.WayCodeEnum.COM_PORT_FTP.toString(), comId);
        } else if (records.size() > 1) {// 有效记录太多则全部作废再新建记录
            records.forEach(record -> record.setState("1"));
            cargoDeclaRecordService.batchUpdateByPrimaryKey(records);
            cargoDeclaRecordService.newRecord(declaration, ComDeclaWay.WayCodeEnum.COM_PORT_FTP.toString(), comId);
        } else {
            CargoDeclaRecord record = records.get(0);
            //广州单一窗口或者符合重复提交状态的记录作废后新建
            //            if (record.getUploadWay().equals(ComDeclaWay.WayCodeEnum.GZ_PORT_HTTPS.toString()) || "TM TS TF".contains(record.getStatus())) {
            record.setState("1");
            cargoDeclaRecordService.updateByPrimaryKeySelective(record);
            cargoDeclaRecordService.newRecord(declaration, ComDeclaWay.WayCodeEnum.COM_PORT_FTP.toString(), comId);
            //            } else {
            //                record.setUpdateTime(new Date());
            //                cargoDeclaRecordService.updateByPrimaryKeySelective(record);
            //            }
        }
    }

    /**
     * 下载各公司国版单一窗口客户端ftp目录下的回执文件
     * 1、读取各公司国版单一窗口配置
     * 2、通过ftp下载文件
     * 3、删除ftp上的文件
     */
    public void downloadSWClientReceipt() {
        // 遍历配置表
        // 拿到个公司 活动状态、ftp地址、端口、账号、密码
        ComDeclaWay query = new ComDeclaWay();
        query.setStatus("1");
        query.setWayCode(ComDeclaWay.WayCodeEnum.COM_PORT_FTP.toString());
        List<ComDeclaWay> ways = comDeclaWayService.selective(query);
        for (ComDeclaWay way : ways) {
            Thread thread = new Thread(() -> {
                Map<String, String> propMap = way.getPropMap();
                String ftpUrl = propMap.get(ComDeclaProp.PropKey.FTP_URL.toString());
                String ftpPort = propMap.get(ComDeclaProp.PropKey.FTP_PORT.toString());
                String ftpAccount = propMap.get(ComDeclaProp.PropKey.FTP_ACCOUNT.toString());
                String ftpPwd = propMap.get(ComDeclaProp.PropKey.FTP_PWD.toString());
                downloadSWClientReceipt(ftpUrl, ftpPort, ftpAccount, ftpPwd);
            });
            downloadThread.put(way.getComId(), thread);
            thread.start();
        }
    }

    /**
     * 下载FTP目录下的文件
     *
     * @param ftpUrl     ftp地址
     * @param ftpPort    端口
     * @param ftpAccount 账号
     * @param ftpPwd     密码
     */
    private void downloadSWClientReceipt(String ftpUrl, String ftpPort, String ftpAccount, String ftpPwd) {
        FtpUtil ftpUtil = new FtpUtil();
        // 一线通保存回执的目录
        String dir = getGtimpReceiptFileNotReadDirPath();
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            ftpUtil.connect(ftpUrl, Integer.valueOf(ftpPort), ftpAccount, ftpPwd, "");
            ftpUtil.downloadThenDel("InBox", "", dirFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ftpUtil.closeServer();
        }
    }

    /**
     * 一线通保存回执的目录
     * 回执未被解析
     */
    private String getGtimpReceiptFileNotReadDirPath() {
        return SpringUtils.getBean(Environment.class).getProperty("file.singlewindow.parseDir");
    }

    /**
     * 一线通保存回执的目录
     * 回执已解析
     */
    private String getGtimpReceiptFileBackupDirPath() {
        return SpringUtils.getBean(Environment.class).getProperty("file.singlewindow.backupDir");
    }

    /**
     * 一线通保存xml报文的目录
     * 回执已解析
     */
    private String getGtimpXMLDirPath() {
        return SpringUtils.getBean(Environment.class).getProperty("file.singlewindow.tempDir");
    }

    /**
     * 解析所有待解析的回执文件
     * 1、进入带解析目录，扫描所有文件
     * 2、逐个文件解析，每解析完一个，将文件移到另一个目录
     */
    public void parseAllSWClentReceiptFile() {
        // 一线通保存回执的目录
        String notReadDirPath = getGtimpReceiptFileNotReadDirPath();
        String backUpPath = getGtimpReceiptFileBackupDirPath();
        File notReadDir = new File(notReadDirPath);
        File backDir = new File(backUpPath);
        if (!notReadDir.exists() || !notReadDir.isDirectory()) {
            return;
        }
        File[] receiptFiles = notReadDir.listFiles();
        if (ArrayUtils.isNotEmpty(receiptFiles)) {
            for (File receiptFile : receiptFiles) {
                // 解析文件
                try {
                    parseReceiptFile(receiptFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    // 移动文件
                    FileUtils.moveToDirectory(receiptFile, backDir, true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 解析单个回执文件
     * 1、将文件内容转为对象
     * 2、判断回执文件类型
     * 3、判断回执文件代码
     * 4、更新状态，假如已经进入海关申报的流程，要回填报关单号
     *
     * @param receiptFile 回执文件。 内容格式详见 《单一窗口客户端导入接口说明(v0.7)(1).doc》 P6-8
     */
    @Transactional
    public void parseReceiptFile(File receiptFile) {
        // step1 解析文件
        SWClientResp resp = readSWClientRespFile(receiptFile);
        if (resp == null) {
            return;
        }
        // step2 更新状态
        String fileName = receiptFile.getName();
        CargoDeclaRecord record;
        String status;
        // 以Successed或Failed开头的文件名，是暂存的回执。
        if (StringUtils.startsWithAny(fileName, "Successed", "Failed")) {
            String businessId = fileName.split("_")[1].toUpperCase();
            record = cargoDeclaRecordService.selectByBusinessAndUploadWay(businessId, ComDeclaWay.WayCodeEnum.COM_PORT_FTP.toString());
            if (record == null) {
                return;
            }
            if (resp.isSuccessResult()) {
                status = "TS"; // 暂存成功
                String jsonRtData = resp.getRetData();
                JSONObject jsonObject = JSON.parseObject(jsonRtData);
                String seqNo = jsonObject.getString("cusCiqNo"); // 获取关联关检号
                record.setInvNo(seqNo);
            } else {
                status = "TUF"; // 暂存失败
                record.setFailInfo(resp.getFailInfo());
            }

            record.setStatus(status);
            record.setUpdateTime(new Date());
        } else {
            // 以Receipt开头的是后续的申报业务的回执
            // 进入申报阶段
            String ivnNo = fileName.split("_")[1].toUpperCase();
            record = cargoDeclaRecordService.selectByInvNoAndUploadWay(ivnNo, ComDeclaWay.WayCodeEnum.COM_PORT_FTP.toString());
            if (record == null) {
                return;
            }
            if (resp.isSuccessResult()) {
                SWClientRespReceipt lastReceipt = resp.getRetDataSubReceipt().get(0);
                String entryId = lastReceipt.getEntryId(); // 报关单号
                if (StringUtils.isNotEmpty(entryId)) {
                    record.setEntryNo(lastReceipt.getEntryId());

                    // 同步更新报关单的报关单号
                    Declaration declaration = new Declaration();
                    declaration.setId(record.getDid());
                    declaration.setSno(entryId);
                    declarationService.updateByPrimaryKeySelective(declaration);

                    //更新新港系统报关单号
                    try {
                        new CtmsServiceClient().updateSno(record.getDid(), entryId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                record.setStatus(lastReceipt.getChannel());
            }
            record.setFailInfo(resp.getFailInfo());
        }
        cargoDeclaRecordService.updateByPrimaryKeySelective(record);
    }

    private void parseReceiptFileT(File receiptFile) {
        // step1 解析文件
        SWClientResp resp = readSWClientRespFile(receiptFile);
        if (resp == null) {
            return;
        }
        // step2 更新状态
        String fileName = receiptFile.getName();
        CargoDeclaRecord record;
        String status;
        // 以Successed或Failed开头的文件名，是暂存的回执。
        if (StringUtils.startsWithAny(fileName, "Successed", "Failed")) {
            String businessId = fileName.split("_")[1].toUpperCase();
            if (resp.isSuccessResult()) {
                status = "TS"; // 暂存成功
                String jsonRtData = resp.getRetData();
                JSONObject jsonObject = JSON.parseObject(jsonRtData);
                String seqNo = jsonObject.getString("cusCiqNo"); // 获取关联关检号
            } else {
                status = "TUF"; // 暂存失败
            }

        } else {
            // 以Receipt开头的是后续的申报业务的回执
            // 进入申报阶段
            String ivnNo = fileName.split("_")[1].toUpperCase();
            if (resp.isSuccessResult()) {
                SWClientRespReceipt lastReceipt = resp.getRetDataSubReceipt().get(0);
                String entryId = lastReceipt.getEntryId(); // 报关单号
                if (StringUtils.isNotEmpty(entryId)) {

                    // 同步更新报关单的报关单号
                    Declaration declaration = new Declaration();
                    declaration.setSno(entryId);
                    declarationService.updateByPrimaryKeySelective(declaration);
                }
            }
        }
    }

    /**
     * 从客户端回执文件中读出所有回执
     *
     * @param file 客户端回执文件
     * @return 客户端回执对象
     */
    private SWClientResp readSWClientRespFile(File file) {
        SWClientResp respObj = new SWClientResp();
        try {
            InputStream in = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new UnicodeReader(in, "UTF-8"));
            StringBuilder sb = new StringBuilder();

            String tmp = reader.readLine();
            while (tmp != null && tmp.trim().length() > 0) {
                sb.append(tmp);
                tmp = reader.readLine();
            }
            reader.close();
            in.close();

            String fileContent = sb.toString();
            if (StringUtils.isNotEmpty(fileContent)) {
                fileContent = fileContent.replaceAll("\n", "");
                Document xmlReps = XMLUtils.getDocumentFromXMLString(fileContent);
                if (file.getName().contains("Receipt")) {
                    respObj.setResultFlag(XMLUtils.readText(xmlReps, "ResultFlag"));
                    respObj.setFailCode(XMLUtils.readText(xmlReps, "FailCode"));
                    respObj.setFailInfo(XMLUtils.readText(xmlReps, "FailInfo"));
                    respObj.setBizSeqNo(XMLUtils.readText(xmlReps, "BizSeqNo"));
                    respObj.setBizType(XMLUtils.readText(xmlReps, "BizType"));
                    List<Element> receiptEles = XMLUtils.getElements(xmlReps, "Receipt");
                    respObj.setReceipt(receiptEles);
                } else {
                    respObj.setResultFlag(XMLUtils.readText(xmlReps, "resultFlag"));
                    respObj.setFailCode(XMLUtils.readText(xmlReps, "failCode"));
                    respObj.setFailInfo(XMLUtils.readText(xmlReps, "failInfo"));
                    respObj.setBizSeqNo(XMLUtils.readText(xmlReps, "bizSeqNo"));
                    respObj.setBizType(XMLUtils.readText(xmlReps, "bizType"));
                    respObj.setRetData(XMLUtils.readText(xmlReps, "retData"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respObj;
    }

    /**
     * 查询当前公司开通了哪些申报方式
     */
    public String currentCompanyUploadWays() {
        StringBuilder wayCodes = new StringBuilder();

        //查询当前公司开通了哪些申报方式
        String currentCompanyId = LoginUtil.getLoginUser().getCompany().getId();
        ComDeclaWay query = new ComDeclaWay();
        query.setStatus("1");
        query.setComId(currentCompanyId);

        List<ComDeclaWay> ways = comDeclaWayService.selective(query);
        for (ComDeclaWay way : ways) {
            wayCodes.append(way.getWayCode());
            wayCodes.append(",");
        }
        if (wayCodes.length() > 0) {
            wayCodes.deleteCharAt(wayCodes.length() - 1);
        }
        return wayCodes.toString();
    }

    /**
     * 将报关资料通过ftp传到对应客户端文件夹下
     */
    public void uploadToSWClient() {
        //获取任务队列
        List<String> uploadQueue = new ArrayList<>();
        int queueSize = jedisClientCluster.size("ComDeclationWaitingUpload");
        for (int i = 0; i < queueSize; i++) {
            uploadQueue.add(jedisClientCluster.rightPop("ComDeclationWaitingUpload", String.class));
        }
        Map<String, List<String>> queueMap = uploadQueue.stream().collect(Collectors.groupingBy(x -> x.split("-")[0], Collectors.mapping(x -> x.split("-")[1], Collectors.toList())));
        for (String comId : queueMap.keySet()) {
            Thread thread = new Thread(() -> {
                List<String> xmlFilePaths = new ArrayList<>();
                List<String> dids = queueMap.get(comId);
                List<CargoDeclaRecord> cargoDeclaRecords = cargoDeclaRecordService.selectByDid(dids);
                cargoDeclaRecords.forEach(cargoDeclaRecord -> cargoDeclaRecord.setStatus("TU"));
                cargoDeclaRecordService.batchUpdateByPrimaryKey(cargoDeclaRecords);
                for (String did : dids) {
                    try {
                        xmlFilePaths.add(buildXML(did));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                ComDeclaWay way = comDeclaWayService.findByComId(comId);
                Map<String, String> propMap = way.getPropMap();
                String ftpUrl = propMap.get(ComDeclaProp.PropKey.FTP_URL.toString());
                String ftpPort = propMap.get(ComDeclaProp.PropKey.FTP_PORT.toString());
                String ftpAccount = propMap.get(ComDeclaProp.PropKey.FTP_ACCOUNT.toString());
                String ftpPwd = propMap.get(ComDeclaProp.PropKey.FTP_PWD.toString());
                FtpUtil ftpUtil = new FtpUtil();
                List<String> success = new ArrayList<>();
                try {
                    ftpUtil.connect(ftpUrl, Integer.valueOf(ftpPort), ftpAccount, ftpPwd, "OutBox");
                    for (String xmlFilePath : xmlFilePaths) {
                        File xmlFile = new File(xmlFilePath);
                        String tempName = xmlFile.getName().replace(".xml", ".temp");
                        if (ftpUtil.uploadFile(tempName, xmlFilePath)) {
                            if (ftpUtil.rename(tempName, xmlFile.getName())) {
                                success.add(xmlFile.getName().split("_")[1].replace(".xml", ""));
                                xmlFile.delete();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    ftpUtil.closeServer();
                }
                cargoDeclaRecords.forEach(cargoDeclaRecord -> {
                    if (success.contains(cargoDeclaRecord.getDid())) {
                        cargoDeclaRecord.setStatus("TUS");
                    } else {
                        cargoDeclaRecord.setStatus("TF");
                    }
                });
                cargoDeclaRecordService.batchUpdateByPrimaryKey(cargoDeclaRecords);
            });
            uploadThread.put(comId, thread);
            thread.start();
        }
    }

    public static void main(String[] args) {
        new SingleWindow().parseReceiptFileT(new File("F:\\Successed_BE201712180214_f0fc94326059fb8c016067f6b12b0e02(SWDEC001_G)_20171218011914230.xml"));
    }
}
